﻿using MQTTnet;
using MQTTnet.Protocol;
using System.Text;

namespace mqtt
{
    public class MqttUtils
    {
        private IMqttClient mqttClient;
        private MqttClientOptions options;

        /// <summary>
        /// 构造函数，初始化MQTT服务器参数
        /// </summary>
        public MqttUtils(string server = "localhost", int port = 1883)
        {
            var factory = new MqttClientFactory();
            mqttClient = factory.CreateMqttClient();
            options = new MqttClientOptionsBuilder()
                .WithTcpServer(server, port)
                .Build();
        }

        /// <summary>
        /// 连接到MQTT服务器
        /// </summary>
        public async Task ConnectAsync()
        {
            if (!mqttClient.IsConnected)
            {
                await mqttClient.ConnectAsync(options,CancellationToken.None);
            }
        }

        /// <summary>
        /// 发布消息
        /// </summary>
        public async Task PublishAsync(string topic, string payload, int qos = 1)
        {
            var message = new MqttApplicationMessageBuilder()
                .WithTopic(topic)
                .WithPayload(Encoding.UTF8.GetBytes(payload))
                .WithQualityOfServiceLevel((MqttQualityOfServiceLevel)qos)
                .Build();

            if (mqttClient.IsConnected)
            {
                await mqttClient.PublishAsync(message);
            }
        }

        /// <summary>
        /// 订阅主题并设置消息回调
        /// </summary>
        public async Task SubscribeAsync(string topic, Action<string, string> onMessage)
        {
            mqttClient.ApplicationMessageReceivedAsync += e =>
            {
                string recvTopic = e.ApplicationMessage.Topic;
                string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                onMessage?.Invoke(recvTopic, payload);
                return Task.CompletedTask;
            };

            if (mqttClient.IsConnected)
            {
                await mqttClient.SubscribeAsync(topic);
            }
        }

        /// <summary>
        /// 断开与MQTT服务器的连接
        /// </summary>
        /// <returns></returns>
        public async Task DisconnectAsync()
        {
            if (mqttClient != null && mqttClient.IsConnected)
            {
                await mqttClient.DisconnectAsync();
            }
        }
        /// <summary>
        /// 检查是否已连接到MQTT服务器
        /// </summary>
        /// <returns></returns>
        public bool IsConnected()
        {
            return mqttClient != null && mqttClient.IsConnected;
        }
    }
}